package FinanceAccountSubject

import (
	"ToolLibray/jwtx"
	"context"
	"property_api/internal/svc"
	"property_api/internal/types"
	"property_api/utils/result"
	"property_api/utils/tree"
	"property_api/utils/xform"
	"property_service/property_service"

	"github.com/zeromicro/go-zero/core/logx"
)

type (
	PagesLogic struct {
		logx.Logger
		ctx    context.Context
		svcCtx *svc.ServiceContext
	}
	dept struct {
		types.FinanceAccountSubject
		Children []tree.NodeWithChildren `json:"children"`
	}
)

func (d *dept) GetID() int64 {
	//TODO implement me
	return d.ID
}

func (d *dept) GetParentID() int64 {
	//TODO implement me
	return d.ParentID
}

func (d *dept) GetChildren() []tree.NodeWithChildren {
	//TODO implement me
	return d.Children
}

func (d *dept) SetChildren(children []tree.NodeWithChildren) {
	d.Children = children
}

func NewPagesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PagesLogic {
	return &PagesLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// Pages 查询财务科目表的分页逻辑
func (l *PagesLogic) Pages(req *types.FinanceAccountSubjectPageReq) (resp *types.PageRes, err error) {
	// 设置租户ID，从上下文中获取
	tenantID := jwtx.GetUserTenantId64(l.ctx)
	// 设置更新用户，从上下文中获取
	userIdStr := xform.Int64ToString(jwtx.GetUserId(l.ctx))

	// 构建查询条件对象，包含所有字段
	where := &property_service.FinanceAccountSubject{
		TenantID:      tenantID,         // 租户ID
		ID:            req.ID,           // 记录ID
		ParentID:      req.ParentID,     // 父级ID
		ParentCode:    req.ParentCode,   //父级编码
		SubjectCode2:  req.SubjectCode2, //模糊查询父级编码
		SubjectCode:   req.SubjectCode,  // 科目编码
		SubjectName:   req.SubjectName,  // 科目名称
		SubjectType:   req.SubjectType,  // 科目类型
		UpdatedAtuser: userIdStr,        // 更新人
	}

	// 调用服务层方法，查询财务科目记录的分页数据
	data, err := l.svcCtx.BasicService.FinanceAccountSubjectPage(l.ctx, &property_service.FinanceAccountSubjectPageReq{
		Page:  req.Page,  // 当前页码
		Limit: req.Limit, // 每页条数
		Where: where,     // 查询条件
	})
	if req.Tree != 1 {
		// 返回分页数据的响应
		return result.SucPage(data, types.FinanceAccountSubject{}).PageEd()
	}
	// 返回分页数据的响应
	// 返回分页数据的响应
	return result.SucPage(data, dept{}, func(value interface{}) interface{} {
		data := value.([]*dept)
		return tree.MakeTreeByID(func() []tree.NodeWithChildren {
			convertedNodes := make([]tree.NodeWithChildren, 0)
			for _, category := range data {
				convertedNodes = append(convertedNodes, category)
			}
			return convertedNodes
		}())
	}).PageEd()
}
